<template>
	<div>
		<!--头部行表单 ：搜索 增加 导出 -->
		<div class="filter-container">
			<el-input v-model="query.keyword" placeholder="搜索用户" style="width: 200px;" @keyup.enter.native="handleSearch" />
			<el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
			<el-button disabled style="margin-left: 10px;" type="primary" :icon="CirclePlus" @click="handleAdd">增加</el-button>
			<el-button :loading="exportLoading" type="primary" :icon="Switch" @click="handleExport">导出</el-button>
		</div>

		<!-- 数据列表 编辑 删除 -->
		<div class="list-container">
			<el-table :data="dataList" border fit highlight-current-row style="width: 100%;" @sort-change="sortChange">
				<el-table-column label="ID" prop="id" width="60" sortable="custom" align="center"></el-table-column>
				<el-table-column label="用户名" prop="name" sortable="custom"></el-table-column>
				<el-table-column label="邮箱" prop="email" sortable="custom"></el-table-column>
				<el-table-column label="电话" prop="phone" sortable="custom"></el-table-column>
				<el-table-column label="性别" prop="gender" width="60" align="center">
					<template #default="{ row }">
						{{ row.gender == 1 ? '男' : '女' }}
					</template>
				</el-table-column>
				<el-table-column label="昵称" prop="nickName" sortable="custom"></el-table-column>
				<el-table-column label="头像" prop="avatar" align="center" width="100">
					<template #default="{ row }">
						<el-avatar size="small" :src="$fullUrl(row.avatar)"></el-avatar>
					</template>
				</el-table-column>

				<el-table-column label="操作" width="240">
					<template #default="scope">
						<el-button link :icon="Edit" @click="handleUpdate(scope.row.id)">编辑</el-button>
						<el-button link :icon="Delete" @click="handleDelete(scope.row.id)">删除</el-button>
						<el-button link :icon="Refresh" @click="handleResetPassWord(scope.row.id)">重置密码</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pagination">
				<el-pagination
					background
					layout="total, prev, pager, next"
					:current-page="query.pageIndex"
					:page-size="query.pageSize"
					:total="totalCount"
					@current-change="handlePageChange"
				></el-pagination>
			</div>
		</div>
		<!-- 编辑弹出框 -->
		<user-edit v-if="editDialogVisible" ref="editDialogRef" @refreshDataList="loadDataList"></user-edit>
	</div>
</template>

<script setup>
import * as UserAPI from '@/api/user.js';
import UserEdit from './components/UserEdit.vue';

import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, CirclePlus, Switch, Edit, Delete,Refresh } from '@element-plus/icons-vue';

const dataList = ref([]); //列表数据
const query = reactive({
	keyword: '',
	pageIndex: 1,
	pageSize: 10,
	orderBy: 'id' //排序字段
}); // 分页查询参数
const totalCount = ref(0); //总记录数
const exportLoading = ref(false); //导出,还没实现
const editDialogVisible = ref(false); //编辑框是否显示

// 获取列表数据
const loadDataList = async () => {
	let result = await UserAPI.getPage(query);
	dataList.value = result.data.list; //返回数据结构参见API文档
	totalCount.value = result.data.totalCount;
};

loadDataList(); // 初始列表数据

// 触发搜索按钮
const handleSearch = () => {
	query.pasgeIndex = 1;
	loadDataList();
};

const editDialogRef = ref(null);
// 增加记录
const handleAdd = async () => {
	ElMessage('管理员是不能增加注册用户的');
};
// 触发导出按钮
const handleExport = async () => {
	// ElMessage('导出，待完成...');
	exportLoading.value = true;
	let EXCEL = await import('@/vendor/Export2Excel');
	const headers = {
		用户Id: 'id',
		用户名: 'name',
		性别: 'gender',
		手机号: 'phone',
		邮箱: 'email',
		昵称: 'nickName'
	};

	try {
		const params = {
			pageIndex: 1,
			pageSize: totalCount.value
		};
		const result = await UserAPI.getPage(params);
		const userList = result.data.list;
		const data = formatJson(headers, userList);
		EXCEL.export_json_to_excel({
			header: Object.keys(headers),
			data,
			filename: '注册用户数据'
		});
		exportLoading.value = false;
		ElMessage.success('导出成功');
	} catch (err) {
		exportLoading.value = false;
		console.log(err);
	}
};

// 将json数据转换成导出excel参数所需要的数组中包数组的格式
const formatJson = (headers, list) => {
	return list.map(item => {
		// 先找到每条员工数据
		return Object.keys(headers).map(key => {
			// 找到每个中文表头key，则headers[key]就是中文表头对应的英文
			if (headers[key] === 'gender') {
				// 转换格式
				return item[headers[key]] === 1 ? '男' : '女';
			}
			return item[headers[key]];
		});
	});
};

// 触发字段排序
const sortChange = ({ prop, order }) => {
	if (prop == 'nickName') {
		prop = 'nick_name';
	}
	if (order === 'ascending') {
		query.orderBy = `${prop} ASC`;
	} else {
		query.orderBy = `${prop} DESC`;
	}
	handleSearch();
};

// 删除操作
const handleDelete = id => {
	// 二次确认删除
	ElMessageBox.confirm('确定要删除吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		// 选择了确认，则删除后端数据库中的记录
		await UserAPI.deleteById(id);
		loadDataList(); //同步列表中的记录
		ElMessage.success('删除成功');
	});
};

// 编辑操作，id为编辑记录的ID
const handleUpdate = async id => {
	editDialogVisible.value = true;
	await nextTick();
	editDialogRef.value.init(id);
};

// 密码重置操作
const handleResetPassWord = id => {
	// 二次确认删除
	ElMessageBox.confirm('确定要重置密码吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		// 选择了确认，则删除后端数据库中的记录
		let password = '123456'; //统一的重置密码
		await UserAPI.resetPasswordById(id, password);
		ElMessage.success('用户密码重置成功！');
	});
};

// 分页导航=======================================
const handlePageChange = val => {
	query.pageIndex = val;
	loadDataList();
};
</script>

<style scoped></style>
